package com.lagou.ipersistence.builder.xml;

import com.lagou.ipersistence.builder.BaseBuilder;
import com.lagou.ipersistence.builder.MapperBuilderAssistant;
import com.lagou.ipersistence.mapping.SQLCommandType;
import com.lagou.ipersistence.mapping.SqlSource;
import com.lagou.ipersistence.mapping.StatementType;
import com.lagou.ipersistence.parsing.XNode;
import com.lagou.ipersistence.scripting.LanguageDriver;
import com.lagou.ipersistence.scripting.xmltags.XMLLanguageDriver;
import com.lagou.ipersistence.session.Configuration;

import java.util.Locale;

/**
 * @author Yan Jiahong
 * Created on 2020/11/12
 */
public class XMLStatementBuilder extends BaseBuilder {
    private final MapperBuilderAssistant builderAssistant;
    private final XNode context;

    public XMLStatementBuilder(Configuration configuration, MapperBuilderAssistant builderAssistant, XNode context) {
        super(configuration);
        this.builderAssistant = builderAssistant;
        this.context = context;
    }

    public void parseStatementNode() {
        String id = context.getStringAttribute("id");
        String parameterType = context.getStringAttribute("parameterType");
        Class<?> parameterTypeClass = resolveClass(parameterType);
        String resultType = context.getStringAttribute("resultType");
        Class<?> resultTypeClass = resolveClass(resultType);
        String nodeName = context.getNode().getNodeName();
        StatementType statementType = StatementType.valueOf(
                context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
        SQLCommandType sqlCommandType = SQLCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
        LanguageDriver lang = new XMLLanguageDriver();
        SqlSource sqlSource = lang.createSqlSource(configuration, context, parameterTypeClass);
        builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, parameterTypeClass,
                null, resultTypeClass, lang);
    }
}
